package com.outlook.flowervowlogin;

import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;

import java.io.File;

public class CommandReg implements CommandExecutor {
    private Main plugin;
    public CommandReg(Main plugin){
        this.plugin = plugin;
    }
    @Override
    public boolean onCommand(CommandSender commandSender, Command command, String s, String[] args){
        try {
            Player p = (Player) commandSender;
            if (command.getName().equalsIgnoreCase("reg")) {
                File dir = new File(Main.instance.getDataFolder(), "Player");
                File playerfile = new File(dir, p.getName() + ".yml");
                if (!playerfile.exists()) {
                if (args.length == 1){
                    p.sendMessage("§a[§a茶§b坂]§a请输入 §a/reg [密码] [重复密码] §a来注册你的账号");
                }
                if (args.length == 2) {
                        String password = args[0];
                            if (args[0].equals(args[1])) {
                                playerfile.createNewFile();
                                FileConfiguration playeryml = YamlConfiguration.loadConfiguration(playerfile);
                                playeryml.set("password", password);
                                playeryml.save(playerfile);
                                p.sendMessage("§a[§a茶§b坂]§a注册成功！马上将您传送至大厅");
                                new BukkitRunnable(){
                                    @Override
                                    public void run(){
                                        ByteArrayDataOutput out = ByteStreams.newDataOutput();
                                        out.writeUTF("Connect");
                                        out.writeUTF(Main.instance.getConfig().getString("LobbyName"));
                                        p.sendPluginMessage(plugin, "BungeeCord", out.toByteArray());
                                    }
                                }.runTaskLater(plugin,10);

                            }else {
                                p.sendMessage("§a[§a茶§b坂]§c两次输入的密码不一致,请重新输入§a/reg [密码] [重复密码]");
                            }
                        } else {
                            p.sendMessage("§a[§a茶§b坂]§c你已经注册过了,请输入§a/l [密码] §c来登录你的账号");

                        }

                }
            }
        }catch (Exception error){
            System.out.println("");
        }
        return true;
    }
}
